/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2017年9月20日
 *******************************************************************************/

package com.hualife.md.member.service.impl;

import java.util.Date;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.hualife.md.common.service.IKvQueryService;
import com.hualife.md.constants.MDConstants;
import com.hualife.md.member.dao.mybatis.entity.SynAdOrganizationalunit;
import com.hualife.md.member.dao.mybatis.entity.SynAdUser;
import com.hualife.md.member.dao.mybatis.mapper.SynAdOrganizationalunitMapper;
import com.hualife.md.member.dao.mybatis.mapper.SynAdUserMapper;
import com.hualife.md.member.service.IActiveDirectoryUserSyn2MDService;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@Service("activeDirectoryUserSyn2MDService")
public class ActiveDirectoryUserSyn2MDServiceImpl implements
		IActiveDirectoryUserSyn2MDService {

	private static final Logger logger = LoggerFactory
			.getLogger(ActiveDirectoryUserSyn2MDServiceImpl.class);

	@Autowired
	private SynAdUserMapper synAdUserMapper;

	@Autowired
	private SynAdOrganizationalunitMapper synAdOrganizationalunitMapper;

	@Autowired
	private IKvQueryService kvQueryService;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.member.service.IActiveDirectoryUserSyn2MDService#syn2Md()
	 */
	@Override
	public void syn2Md() {
		logger.info("开始同步");
		Properties env = new Properties();

		try {

			// String ip = "10.0.3.6";
			// String port = "389";
			// String adminName = "sunxiaodong001@hxlife.com";
			// String adminPassword = "abcd1234*";
			// String searchBase = "OU=华夏人寿保险股份有限公司,DC=hxlife,DC=com";
			// String searchFilter =
			// "(&(objectCategory=person)(objectClass=user)(sAMAccountName=*))";
			String ip = kvQueryService.getValue("ad.ip");
			String port = kvQueryService.getValue("ad.port");
			String adminName = kvQueryService.getValue("ad.user.name");
			String adminPassword = kvQueryService.getValue("ad.user.password");
			String searchBase = kvQueryService.getValue("ad.search.base");
			String searchFilter = kvQueryService.getValue("ad.search.filter");

			String ldapURL = "LDAP://" + ip + ":" + port;// ip:port
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.SECURITY_AUTHENTICATION, "simple");// "none","simple","strong"
			env.put(Context.SECURITY_PRINCIPAL, adminName);
			env.put(Context.SECURITY_CREDENTIALS, adminPassword);
			env.put(Context.PROVIDER_URL, ldapURL);

			LdapContext ctx = new InitialLdapContext(env, null);
			SearchControls searchCtls = new SearchControls();
			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			searchCtls.setReturningAttributes(ADProperties.getAttrNames());
			NamingEnumeration<SearchResult> answer = ctx.search(searchBase,
					searchFilter, searchCtls);

			String sql = " TRUNCATE TABLE syn_ad_user";
			jdbcTemplate.execute(sql);
			while (answer.hasMoreElements()) {
				SearchResult sr = (SearchResult) answer.next();

				Attributes Attrs = sr.getAttributes();
				if (Attrs != null) {
					String samaccountname = "";
					SynAdUser adUser = new SynAdUser();
					Date now = new Date();
					try {
						for (NamingEnumeration<? extends Attribute> ne = Attrs
								.getAll(); ne.hasMore();) {
							Attribute Attr = (Attribute) ne.next();

							String attributeID = Attr.getID().toString();

							if ("sAMAccountName".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								samaccountname = e.next().toString();
								adUser.setSamaccountname(samaccountname);
							}

							if ("userAccountControl".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adUser.setUseraccountcontrol(e.next()
										.toString());
							}

							if ("name".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adUser.setName(e.next().toString());
							}

							if ("mail".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adUser.setMail(e.next().toString());
							}

							if ("description".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adUser.setDescription(e.next().toString());
							}

							if ("department".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adUser.setDepartment(e.next().toString());
							}

							if ("title".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adUser.setTitle(e.next().toString());
							}

							if ("whenCreated".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adUser.setWhencreated(e.next().toString());
							}

							if ("whenChanged".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adUser.setWhenchanged(e.next().toString());
							}
							adUser.setDn(sr.getName());
							adUser.setIssynedtouser(MDConstants.NOT_SYNED);
							adUser.setCreateTime(now);
							adUser.setUpdateTime(now);
						}
					} catch (NamingException e) {
						logger.error("Throw Exception : " + e);
					}

					synAdUserMapper.insertSelective(adUser);
				}

			}
			ctx.close();
		} catch (NamingException e) {
			e.printStackTrace();
			logger.error("Problem searching directory: " + e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.member.service.IActiveDirectoryUserSyn2MDService#synOU2Md
	 * ()
	 */
	@Override
	public void synOU2Md() {
		logger.info("开始同步");
		Properties env = new Properties();

		try {
			// String ip = "10.0.3.6";
			// String port = "389";
			// String adminName = "sunxiaodong001@hxlife.com";
			// String adminPassword = "abcd1234*";
			// String searchBase = "OU=华夏人寿保险股份有限公司,DC=hxlife,DC=com";
			// String searchFilter =
			// "(&(objectCategory=person)(objectClass=user)(sAMAccountName=*))";
			String ip = kvQueryService.getValue("ad.ip");
			String port = kvQueryService.getValue("ad.port");
			String adminName = kvQueryService.getValue("ad.user.name");
			String adminPassword = kvQueryService.getValue("ad.user.password");
			String searchBase = kvQueryService.getValue("ad.search.base");
			String searchFilter = kvQueryService
					.getValue("ad.search.ou.filter");

			String ldapURL = "LDAP://" + ip + ":" + port;// ip:port
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.SECURITY_AUTHENTICATION, "simple");// "none","simple","strong"
			env.put(Context.SECURITY_PRINCIPAL, adminName);
			env.put(Context.SECURITY_CREDENTIALS, adminPassword);
			env.put(Context.PROVIDER_URL, ldapURL);

			LdapContext ctx = new InitialLdapContext(env, null);
			SearchControls searchCtls = new SearchControls();
			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			searchCtls.setReturningAttributes(ADProperties.getAttrNames());
			NamingEnumeration<SearchResult> answer = ctx.search(searchBase,
					searchFilter, searchCtls);

			String sql = " TRUNCATE TABLE syn_ad_organizationalunit";
			jdbcTemplate.execute(sql);
			int size = 0;
			while (answer.hasMoreElements()) {
				SearchResult sr = (SearchResult) answer.next();

				Attributes Attrs = sr.getAttributes();
				if (Attrs != null) {
					SynAdOrganizationalunit adOrgunit = new SynAdOrganizationalunit();
					Date now = new Date();
					try {
						// byte[] GUID = sr.getAttributes().get("objectGUID")
						// .get().toString().getBytes();
						// String strGUID = "";
						// String byteGUID = "";
						//
						// // Convert the GUID into string using the byte format
						// for (int c = 0; c < GUID.length; c++) {
						// byteGUID = byteGUID + "\\"
						// + AddLeadingZero((int) GUID[c] & 0xFF);
						// }
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[3] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[2] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[1] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[0] & 0xFF);
						// strGUID = strGUID + "-";
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[5] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[4] & 0xFF);
						// strGUID = strGUID + "-";
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[7] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[6] & 0xFF);
						// strGUID = strGUID + "-";
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[8] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[9] & 0xFF);
						// strGUID = strGUID + "-";
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[10] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[11] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[12] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[13] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[14] & 0xFF);
						// strGUID = strGUID
						// + AddLeadingZero((int) GUID[15] & 0xFF);
						for (NamingEnumeration<? extends Attribute> ne = Attrs
								.getAll(); ne.hasMore();) {
							Attribute Attr = (Attribute) ne.next();

							String attributeID = Attr.getID().toString();

							if ("uSNCreated".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adOrgunit.setUsncreated(e.next().toString());
							}

							if ("uSNChanged".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adOrgunit.setUsnchanged(e.next().toString());
							}

							if ("name".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adOrgunit.setName(e.next().toString());
							}

							if ("whenCreated".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adOrgunit.setWhencreated(e.next().toString());
							}

							if ("whenChanged".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								adOrgunit.setWhenchanged(e.next().toString());
							}
							adOrgunit.setDn(sr.getName());
							adOrgunit.setIssynedtoou(MDConstants.NOT_SYNED);
							adOrgunit.setCreateTime(now);
							adOrgunit.setUpdateTime(now);
						}
					} catch (NamingException e) {
						logger.error("Throw Exception : " + e);
					}
					size++;
					synAdOrganizationalunitMapper.insertSelective(adOrgunit);
				}
			}
			System.out.println("size:" + size);
			ctx.close();
		} catch (NamingException e) {
			e.printStackTrace();
			logger.error("Problem searching directory: " + e);
		}

	}

	public static String AddLeadingZero(int k) {
		return (k <= 0xF) ? "0" + Integer.toHexString(k) : Integer
				.toHexString(k);
	}

}

/*
 * 修改历史 $Log$
 */